package com.weilele.mvvm.utils.download

import android.app.*
import android.content.*
import android.os.Environment
import com.weilele.mvvm.R
import com.weilele.mvvm.app
import com.weilele.mvvm.utils.activity.getResString
import com.weilele.mvvm.utils.installApk

/**
 * App升级帮助类
 */

object UpdateApkHelper {
    //点击通知栏广播
    private const val ACTION_CLICK_DOWN = "ACTION_CLICK_DOWN"

    //点击取消下载广播
    private const val ACTION_CLICK_CANCEL = "ACTION_CLICK_CANCEL"

    //通知栏动作广播
    private var updateAppReceiver: UpdateAppReceiver? = null

    //上下文，全局的application
    private var context = app

    //下载帮助类
    private val updateApp = DownFileWithNotification().apply {
        downloadCompleteListener = {
            installApk(it)
        }
    }

    /**
     * 开始下载
     */
    fun startDown(url: String) {
        if (updateApp.startDown(
                        context,
                        url,
                        10086,
                        createReceiverIntent(ACTION_CLICK_DOWN),
                        createReceiverIntent(ACTION_CLICK_CANCEL),
                        getResString(R.string.app_name).toString() + ".apk",
                        Environment.DIRECTORY_DOWNLOADS,
                        "apk"
                )
        ) {
            regiestUpdateAppReceiver()
        }
    }

    /**
     * 停止下载
     */
    fun stopDown() {
        updateApp.stopDown()
        unRegiestUpdateAppReceiver()
    }

    /**
     * 通过action创建意图
     */
    private fun createReceiverIntent(action: String): PendingIntent {
        val intent = Intent()
        intent.action = action
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    }

    /**
     * 注册广播
     */
    private fun regiestUpdateAppReceiver() {
        if (updateAppReceiver == null) {
            updateAppReceiver = UpdateAppReceiver()
        }
        val filter = IntentFilter()
        filter.addAction(ACTION_CLICK_CANCEL)
        filter.addAction(ACTION_CLICK_DOWN)
        context.registerReceiver(updateAppReceiver, filter)
    }

    /**
     * 取消注册广播
     */
    private fun unRegiestUpdateAppReceiver() {
        if (updateAppReceiver != null) {
            context.unregisterReceiver(updateAppReceiver)
            updateAppReceiver = null
        }
    }

    /**
     * 安装App
     */
    private fun installApk(result: DownloadBean?) {
        result ?: return
        val file = result.file
        context.installApk(file)
    }

    /**
     * 广播类
     */
    private class UpdateAppReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                ACTION_CLICK_CANCEL -> {
                    stopDown()
                }
                ACTION_CLICK_DOWN -> {
                }
            }
        }
    }
}

